package com.kind.perm.web.demo;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kind.common.client.response.JsonResponseResult;
import com.kind.common.contants.Constants;
import com.kind.common.dto.DataGridResult;
import com.kind.common.enums.ResponseState;
import com.kind.common.exception.ServiceException;
import com.kind.common.persistence.PageView;
import com.kind.common.uitls.DateUtils;
import com.kind.common.uitls.NumberUtils;
import com.kind.perm.core.demo.domain.CommunityDO;
import com.kind.perm.core.demo.service.CommunityService;
import com.kind.perm.core.system.domain.FileDO;
import com.kind.perm.core.system.domain.TableCustomTempletDO;
import com.kind.perm.core.system.service.CoFileService;
import com.kind.perm.core.system.service.TableCustomService;
import com.kind.perm.core.system.service.TableCustomTempletService;
import com.kind.perm.web.common.ExcelUtils;
import com.kind.perm.web.common.controller.BaseController;

/**
 * 
 * Function:小区信息管理控制器. <br/>
 * 
 * @date:2016年5月12日 上午11:18:52 <br/>
 * @author 李明
 * @version:
 * @since:JDK 1.7
 */
@Controller
@RequestMapping("demo/community")
public class CommunityController extends BaseController {
	
	@Autowired
	private CommunityService communityService;
	
	@Autowired
	private CoFileService coFileService;
	
	@Autowired
	private TableCustomService tableCustomService;
	
	@Autowired
	private TableCustomTempletService tableCustomTempletService;

    /**列表页面*/
    private final String LIST_PAGE = "demo/community_list";
    /**表单页面*/
    private final String FORM_PAGE = "demo/community_form";

	/**
	 * 进入到默认列表页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String toListPage() {
		return LIST_PAGE;
	}

	/**
	 * 获取分页查询列表数据.
	 */
	@RequestMapping(value = "selectPageList", method = RequestMethod.GET)
	@ResponseBody
	public DataGridResult selectPageList(CommunityDO query, HttpServletRequest request) {
		PageView<CommunityDO> page = communityService.selectPageList(query);
		return super.buildDataGrid(page);
	}

	/**
	 * 加载添加页面.
	 * 
	 * @param model
	 */
	@RequiresPermissions("demo:community:save")
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String toAdd(Model model) {
		model.addAttribute("entity", new CommunityDO());
		model.addAttribute(Constants.CONTROLLER_ACTION, Constants.CONTROLLER_ACTION_ADD);
		return FORM_PAGE;
	}

	/**
	 * 保存数据.
	 * 
	 * @param entity
	 * @param model
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public JsonResponseResult add(@Valid CommunityDO entity, Model model, HttpServletRequest request) {
        try {
            entity.setCreateDate(new Date());
            communityService.save(entity);
            
            //附件管理 star
            String uploadfiledIds = request.getParameter("uploadfileIds");
            String typefiled = request.getParameter("typefiled");
            if(!"".equals(uploadfiledIds)&&uploadfiledIds.split(",").length>0)
            {
            	coFileService.saveBatch(uploadfiledIds.split(","), new Long((long)entity.getId()), typefiled);
            }
           //附件管理 end
            
            return JsonResponseResult.success();

        }catch (ServiceException e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return JsonResponseResult.build(ResponseState.ERROR_CODE_SERVICE_ERROR.getCode(), e.getMessage());
        }
	}

	/**
	 * 加载修改页面.
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("demo:community:change")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") Long id, Model model) {	
		updateView(id, model);
		return FORM_PAGE;
	}

	/**
	 * 修改数据.
	 * 
	 * @param entity
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public JsonResponseResult update(@Valid @ModelAttribute @RequestBody CommunityDO entity, Model model, HttpServletRequest request) {
        try {
            communityService.save(entity);           
            //附件管理 star
            String uploadfiledIds = request.getParameter("uploadfileIds");
            //附件的类型，需要在页面确定属性<input type="hidden" name="typefiled" id="typefiled" value="community"/>  
            String typefiled = request.getParameter("typefiled");
            if(!"".equals(uploadfiledIds)&&uploadfiledIds.split(",").length>0)
            {
            	coFileService.updateBatch(uploadfiledIds.split(","), new Long((long)entity.getId()), typefiled);
            }
           //附件管理 end       
            return JsonResponseResult.success();

        }catch (ServiceException e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return JsonResponseResult.build(ResponseState.ERROR_CODE_SERVICE_ERROR.getCode(), e.getMessage());
        }
	}

	/**
	 * 删除数据.
	 * 
	 * @param id
	 * @return
	 */
	@RequiresPermissions("demo:community:remove")
	@RequestMapping(value = "remove/{id}")
	@ResponseBody
	public JsonResponseResult remove(@PathVariable("id") Long id) {
	    try {
            if (!NumberUtils.isEmptyLong(id)) {
                communityService.remove(id);
            }
            return JsonResponseResult.success();

        }catch (ServiceException e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return JsonResponseResult.build(ResponseState.ERROR_CODE_SERVICE_ERROR.getCode(), e.getMessage());
        }
	}
	
	/**
	 * 加载查看页面.
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("demo:community:view")
	@RequestMapping(value = "view/{id}", method = RequestMethod.GET)
	public String view(@PathVariable("id") Long id, Model model) {
		model.addAttribute("view", "true");
		updateView(id, model);

		return FORM_PAGE;
	}
	
	/**
	 * 导出信息
	 * @param ids
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("demo:community:export")
	@RequestMapping("export")
	@ResponseBody
	public String export(CommunityDO query,HttpServletRequest request,HttpServletResponse response){
		TableCustomTempletDO entity = new TableCustomTempletDO();
		entity.setJavaBean("CommunityDO");
		List<TableCustomTempletDO> tableCustomTempletlist = tableCustomTempletService.queryList(entity);
		TableCustomTempletDO tableCustomTempletDO = new TableCustomTempletDO();
		if(tableCustomTempletlist.size()>0)
		{
			tableCustomTempletDO = tableCustomTempletlist.get(0);
		}
		else
		{
			return "未设置信息";
		}
		return ExcelUtils.export(communityService.queryList(query), tableCustomService.findTableCustomExport(tableCustomTempletDO.getType()), tableCustomTempletDO.getName()+DateUtils.getDateRandom()+".xls", request, response);
	
	}
	
	private void updateView(Long id, Model model) {
		model.addAttribute("entity", communityService.getById(id));
		model.addAttribute(Constants.CONTROLLER_ACTION, Constants.CONTROLLER_ACTION_UPDATE);
		//获取附件列表   start
		String objectB =Constants.COFILE_COMMUNITY;
		String objectA =Constants.COFILE_FILE;
		List<FileDO> filelist =  coFileService.getBatch(objectA, objectB, id);
		StringBuffer fileIds = new StringBuffer();
		for (FileDO fileDO : filelist) {
			fileIds.append(fileDO.getId()+",");
		}
		model.addAttribute("filelist", filelist);
		model.addAttribute("fileIds", fileIds);
		//获取附件列表   end
	}

}
